﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Sherwood.Mvc
{
    public static class ObjectExtensions
    {

        /// <summary>
        /// Builds a dictionary from the object's properties
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public static Dictionary<string, object> ToPropertyDictionary(this object o)
        {
            if (o == null)
                return null;
            return o.GetType().GetProperties()
                .Select(p => new KeyValuePair<string, object>(p.Name, p.GetValue(o, null)))
                .ToDictionary();
        }

        /// <summary>
        /// Builds a dictionary from the object's properties (as string values)
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public static Dictionary<string, string> ToPropertyStringDictionary(this object o)
        {
            if (o == null)
                return null;
            return o.GetType().GetProperties()
                .Where(p => p.GetIndexParameters().GetLength(0) == 0)
                .Select(p => new KeyValuePair<string, string>(p.Name, p.GetValue(o, null).ToEmptyOrString()))
                .ToDictionary();
        }

        /// <summary>
        /// Returns an empty string for null objects, or otherwise object.ToString()
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public static string ToEmptyOrString(this object o)
        {
            return o == null ? "" : o.ToString();
        }

        public static Dictionary<K, V> ToDictionary<K, V>(this IEnumerable<KeyValuePair<K, V>> list)
        {
            return list.ToDictionary(kv => kv.Key, kv => kv.Value);
        }
    }
}
